<template>
  <div class="w-full" :style="{ height: `${screenHeight *0.99}px` }">
    <Grid>
      <template #toolbarButtons>
        <el-button type="primary" @click="addCodingRules">添加层级定义</el-button>
      </template>
      <template #action="{ row }">
        <el-button link type="primary" @click="openModalEvent(row,2)">查看</el-button>
        <el-button link type="primary" @click="openModalEvent(row,1)">编辑</el-button>
        <el-button link type="primary" @click="delRowEvent(row)">删除</el-button>
      </template>
    </Grid>
    <!-- modal弹窗 -->
     <Modal class="w-[40%]" :title="modalType === 0 ? '新增层级定义' : modalType === 1 ? '修改层级定义' : '查看层级定义'">
      <el-form :model="modalForm" label-width="auto" ref="modalFormRef" :rules="modalFormRule" :disabled="modalType === 2" style="max-width: 500px;">
        <el-form-item prop="productType" label="产品类型">
          <el-input v-model="modalForm.productType"></el-input>
        </el-form-item>
        <el-form-item prop="levelName" label="层级名称">
          <el-input v-model="modalForm.levelName"></el-input>
        </el-form-item>
        <el-form-item prop="levelCode" label="层级编码">
          <el-input v-model="modalForm.levelCode"></el-input>
        </el-form-item>
        <el-form-item prop="levelSeq" label="层级顺序">
          <el-input v-model="modalForm.levelSeq"/>
        </el-form-item>
        <el-form-item prop="quantityPerUnit" label="每单位包含数量">
          <el-input v-model="modalForm.quantityPerUnit"></el-input>
        </el-form-item>
      </el-form>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
//@ts-ignore
import type { VbenFormProps } from "#/adapter/form";
import { useRouter,useRoute } from "vue-router";
import type { VxeGridProps, VxeGridListeners } from "#/adapter/vxe-table";
import { ElMessage, ElMessageBox, ElInput,ElForm,ElFormItem, ElDialog,ElButton,ElLoading,ElTag,ElDatePicker,ElNotification,formatter} from "element-plus";
import { Button, Upload, RadioButton, RadioGroup } from "ant-design-vue";
import { useVbenVxeGrid } from "#/adapter/vxe-table";
import { confirm,useVbenModal } from '@vben/common-ui';
import { nextTick, ref, onUnmounted, onMounted,reactive, unref, watch } from "vue";
import { dealVxeGridFilterParameter } from "#/utils/tools";
import { reqPackagingLevelList,reqSavePackagingLevel,reqUpdatePackagingLevel,reqDeletePackagingLevel } from "#/api/productionPlan";
const router = useRouter();
//@ts-ignore
import { useOtherStore } from "#/store/index.ts";
const otherStore = useOtherStore();

const screenHeight = ref<number>(window.innerHeight);

const handleResize = () => {
  screenHeight.value = window.innerHeight;
}
onMounted(() => {
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
   window.removeEventListener("resize", handleResize);
});

const filterParams = ref(null);
const count = ref(0);
const modalType = ref(0);   //0-添加 1-编辑 2-查看
const modalFormRef = ref(null);
const modalForm = reactive({
  id:"",
  productType:"",
  levelName:"",
  levelCode:"",
  levelSeq:"",
  quantityPerUnit:"",
  isActive:false
});
const modalFormRule = reactive({
  productType: [
    { required:true, message:'请输入产品类型',trigger:'blur' }
  ],
  levelName: [
    { required:true, message:'请输入层级名称',trigger:'blur' }
  ],
  levelCode: [
    { required:true, message:'请输入层级编码',trigger:'blur' }
  ],
  levelSeq: [
    { required:true, message:'请输入层级顺序',trigger:'blur' }
  ],
  quantityPerUnit: [
    { required:true, message:'请输入每单位包含数量',trigger:'blur' }
  ]
})

let gridFilterParameter = null;

const gridOptions: VxeGridProps = ref({
  columns: [
    { title: "#", type: "seq", width: 50 },
    {
      field:"productType",
      title:"产品类型",
      width:""
    },
    {
      field:"levelName",
      title:"层级名称",
      width:""
    },
    { 
      field:"levelCode",
      title:"层级编码",
      width:""
    },
    { 
      field:"levelSeq",
      title:"层级顺序",
      width:""
    },
    { 
      field:"quantityPerUnit",
      title:"每单位包含数量",
      width:""
    },
    {
      field:"isActive",
      title:"是否启用",
      width:"",
      cellRender:{
        name:"ElSwitch",
        change:(option) => switchChangeEvent(option)
      },
    },
    {
      fixed: "right",
      slots: { default: "action" },
      title: "操作",
      width: 210
    }
  ],
  toolbarConfig: {
    search: false,
    custom: true,
    refresh: true,
    zoom: true,
    slots: {
      buttons: 'toolbarButtons'
    }
  },
  editConfig: {
    trigger: 'click',
    mode: 'cell',
    showStatus: true,
    autoClear: false
  },
  filterConfig: {
    remote: true
  },
  rowConfig: {
    isCurrent: true,
    isHover: true
  },
  keepSource: true,
  pagerConfig: {
    enabled: true,
    pageSize: 20,
    pageSizes: [10, 20, 30, 50, 100]
  },
  height: "auto",
  autoResize:true,
  proxyConfig: {
    autoLoad: true,
    ajax: {
      query: async ({ page }, formValues) => await vxeTableIQueryEvent({page, formValues})
    }
  }
});

const gridEvents: VxeGridListeners = {
  filterChange({ filterList }) {
    gridOptions.loading = true;
    gridFilterParameter = dealVxeGridFilterParameter(filterList);
    gridApi.query();
  }
};

const [Grid, gridApi] = useVbenVxeGrid({formOptions:null,gridOptions:gridOptions,gridEvents:gridEvents});
const [Modal, modalApi] = useVbenModal({ draggable:true,closeOnClickModal:false,onConfirm:modalConfirm,onBeforeClose:clearModalFormData });

const vxeTableIQueryEvent = async (option) => {
  try {
    const { page,formValues } = option;
    const params = {
      page: page.currentPage,
      size: page.pageSize
    };
    if(gridFilterParameter) Object.assign(params,gridFilterParameter);
    const response = await reqPackagingLevelList(params);
    return {
      total: response.data.totalElements,
      items: response.data.content
    };
  } catch (error) {
    ElNotification({title:'请求失败',message:'获取层级定义列表失败',type:'error'});
    return { total: 0, items: [] };
  }
};

const hasEditStatus = (row: any) => {
  const grid = gridApi.grid;
  if (grid) {
    return grid.isEditByRow(row);
  }
}
const cancelRowEvent = (row:any) => {
  const grid = gridApi.grid;
  if (grid) {
    grid.clearEdit().then(() => {
      grid.revertData(row);
    })
  }
}

const openModalEvent = (row:any,type:number = 0) => {
  modalType.value = type;
  const { id,productType,levelName,levelCode,levelSeq,quantityPerUnit,isActive } = row;
  modalForm.id = id;
  modalForm.productType = productType;
  modalForm.levelName = levelName;
  modalForm.levelCode = levelCode;
  modalForm.levelSeq = levelSeq;
  modalForm.quantityPerUnit = quantityPerUnit;
  modalForm.isActive = isActive;
  modalApi.open();
}

async function modalConfirm(){
    const { id,productType,levelName,levelCode,levelSeq,quantityPerUnit,isActive } = modalForm;
    let checkResult = false;
    await modalFormRef.value.validate((valid:boolean,fields:any) => {
        if(valid) checkResult = true;
    });
    if(!checkResult) return;
    if(unref(modalType) == 0){
        reqSavePackagingLevel(modalForm).then(response => {
            ElNotification({title:'提示',message:'层级定义添加成功',type:'success'});
            modalApi.close();
            gridApi.query();
        },error => {
            ElNotification({title:'提示',message:'层级定义添加失败',type:'error'});
        })
    }
    if(unref(modalType) == 1){
        reqUpdatePackagingLevel(modalForm).then(response => {
            if(response.code == 200){
                ElNotification({title:'提示',message:`层级定义更新成功`,type:'success'});
                gridApi.query();
            }
        },error => {
            ElNotification({title:'提示',message:`层级定义更新失败`,type:'error'});
        })
    }
}

const switchChangeEvent = (option) => {
    const { row,column,changeValue } = option;
    reqUpdatePackagingLevel(row).then(response => {
        if(response.code == 200){
            ElNotification({title:'提示',message:`层级定义${changeValue ? '启用' : '关闭'}成功`,type:'success'});
            gridApi.query();
        }
    },error => {
        ElNotification({title:'提示',message:`层级定义${changeValue ? '启用' : '关闭'}失败`,type:'error'});
    })
}


const addCodingRules = () => {
  modalType.value = 0;
  modalApi.open();
}

const delRowEvent = (row:any) => {
  ElMessageBox.confirm('确定删除该层级定义吗?','提示').then(() => {
    reqDeletePackagingLevel(row).then(response => {
      ElNotification({title:'提示',message:"删除成功",type:'success'});
      gridApi.query();
    },error => {
      ElNotification({title:'提示',message:"删除失败,请重试",type:'error'});
    })
  })
}

const dealStatus = (status:number|string = 0) => {
  status = Number(status);
  let desc = "";
  switch (status) {
    case 0:
      desc = "创建";
      break;
    case 1:
      desc = "生效";
      break;
    case 2:
      desc = "完成";
      break;
    case 3:
      desc = "关闭";
      break;
    case 4:
      desc = "取消";
      break;
    default:
      desc = "未知";
  }
  return desc;
}

function clearModalFormData(){
  modalForm.id = "";
  modalForm.productType = "";
  modalForm.levelName = "";
  modalForm.levelCode = "";
  modalForm.levelSeq = "";
  modalForm.quantityPerUnit = "";
  modalForm.isActive = false;
}
</script>

<style lang="scss" scoped>
.conetnt-page{
  width: 100%;
  height:100vh;
  box-sizing: border-box;
}
.page-top{
  width: 100%;
  height:50px;
  padding: 0 10px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
}
.page-box{
  width: 100%;
  height:calc(100% - 50px);
}

:deep(.el-form-item__content){
  flex-wrap: wrap !important;
}
</style>
